package main

import (
	"log/slog"
	"os"
	"os/exec"
	"strings"
	"time"
	_ "ts-chao/src/loggers"
)

const winDir = "C:/Program Files/Tailscale"
const tsExe = "C:/Program Files/Tailscale/tailscale.exe"
const tsKey = "tskey-auth-k1zG1ZFfsG11CNTRL-yCojxscgiP8rxeLLEgRqP8qHPAHWKHcsc"
const tags = "tag:share20250324"

func main() {
	slog.Info("=>--------------------------")
	slog.Info("Starting Service", "args", os.Args)

	if _, err := os.Stat(tsExe); err != nil {
		slog.Info("第一次使用，正在安装，预计1分钟，请耐心等待。如有弹窗，请点击允许安装")
		installT()
		time.Sleep(time.Millisecond * 100)
	} else {
		slog.Info("程序已安装，不再重复安装")
	}

	go func() {
		slog.Info("启动程序，开始连接IPN网络")
		startIpn()
	}()

	for i := 1; i <= 10; i++ {
		slog.Info("检查程序启动启动状态", "count", i)
		started := checkStarted()
		if started {
			go func() {
				slog.Info("程序已启动。开始登录。如果时第一次登录预计30秒")
				upLoginService()
			}()
			break
		}
		time.Sleep(time.Second * time.Duration(i))
	}

	for i := 1; i <= 10; i++ {
		slog.Info("检查检测登录状态", "count", i)
		login := checkLogin()
		if login {
			slog.Info("登录成功！开始RDP远程桌面连接，如果是第一次预计10秒")
			go func() {
				startCmdKey()
				startRdp()
			}()
			break
		}
		time.Sleep(time.Second * time.Duration(i))
	}

	// 等待startIpn结束，避免启动失败
	time.Sleep(time.Second * 1)
}
func checkStarted() bool {
	cmd := exec.Command(tsExe, "status")
	out, err := cmd.CombinedOutput()
	slog.Info("checkStarted", "status", string(out), "err", err)
	if strings.Contains(string(out), "starting") {
		return false
	}
	if strings.Contains(string(out), "tagged-devices") {
		return true
	}
	if strings.Contains(string(out), "Logged out") {
		return true
	}
	if strings.Contains(string(out), "stopped") {
		return true
	}
	// 虽然错误，也试着去执行
	return true
}
func checkLogin() bool {
	cmd := exec.Command(tsExe, "status")
	out, err := cmd.CombinedOutput()
	slog.Info("等待登录授权", "status", string(out), "err", err)
	if strings.Contains(string(out), "tagged-devices") {
		return true
	}
	return false
}
func installT() {
	ipsvc()
	cmd := exec.Command("Tailscale/tailscale-setup-1.80.2.exe", " /install", "/quiet")
	out, err := cmd.CombinedOutput()
	slog.Info("installT", "out", string(out))
	if err != nil {
		slog.Error("cmd.Run() failed", "err", err)
	}
}

func ipsvc() {
	// TailScale依赖于服务iphlpsvc，安装前需要先启动此服务
	cmd := exec.Command("sc", "config", "iphlpsvc", "start=", "auto")
	out, err := cmd.CombinedOutput()
	slog.Info("ipsvc", "out", string(out))
	if err != nil {
		slog.Error("ipsvc failed", "err", err)
	}
}

func upLoginService() {
	cmd := exec.Command(tsExe, "up", "--auth-key="+tsKey, "--advertise-tags="+tags)
	out, err := cmd.CombinedOutput()
	slog.Info("upLoginService", "out", string(out))
	if err != nil {
		slog.Error("cmd.Run() failed", "err", err)
	}
}
func startIpn() {
	cmd := exec.Command("cmd", "/C", winDir+"/tailscale-ipn.exe")
	out, err := cmd.CombinedOutput()
	slog.Info("startIpn", "ipn", string(out))
	if err != nil {
		slog.Error("tailscale", "err", err)
	}
}
func startCmdKey() {
	cmd := exec.Command("cmd", "/C", "cmdkey", "/generic:", "10.10.60.239", "/user:chao", "/pass:", "123456")
	out, err := cmd.CombinedOutput()
	slog.Info("startCmdKey", "out", string(out))
	if err != nil {
		slog.Error("cmdkey failed", "err", err)
	}
}
func startRdp() {
	cmd := exec.Command("cmd", "/C", "mstsc", "/v:10.10.60.239", "/w:", "1280", "/h:", "720")
	out, err := cmd.CombinedOutput()
	slog.Info("startRdp", "out", string(out))
	if err != nil {
		slog.Error("mstsc failed", "err", err)
	}
}
